package org.csu.canteen.service;

import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
@Service
public class VerificationService {
    public VerificationService(){

    }

    //验证码字符集
    private static final String CHAR_STRING="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int WIDTH=120;
    private static final int HEIGHT=40;
    private static final int CHAR_COUNT=4;//验证码字符数

    //随机生成验证码字符串
    public static String generateVerificationCode(){
        Random random=new Random();
        StringBuilder verificationCode=new StringBuilder(CHAR_COUNT);
        for(int i=0;i<CHAR_COUNT;i++){
            verificationCode.append(CHAR_STRING.charAt(random.nextInt(CHAR_STRING.length())));
        }
        return verificationCode.toString();
    }


    //生成验证码图片
    public static BufferedImage generateImage(String verificationCode){
        BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics2D g=image.createGraphics();
        //设置背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0,0,WIDTH,HEIGHT);
        //设置字体
        g.setFont(new Font("Arial",Font.BOLD,24));
        //绘制验证码
        Random random=new Random();
        for(int i=0;i<verificationCode.length();i++){
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawString(String.valueOf(verificationCode.charAt(i)),i*20+10,30);

        }

        //添加干扰线
        for (int i = 0; i < 4; i++) {
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            int x1=random.nextInt(WIDTH);
            int y1=random.nextInt(HEIGHT);
            int x2=random.nextInt(WIDTH);
            int y2=random.nextInt(HEIGHT);
            g.drawLine(x1,y1,x2,y2);

        }
        g.dispose();//销毁画笔
        return image;
    }

}
